<template>
  <div class="editor">
    <div ref="DivRef" :style="{ height: `${height}px` }"></div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  onMounted,
  onBeforeUnmount,
  defineProps,
  withDefaults,
  defineEmits,
  reactive
} from 'vue'
import E from 'wangeditor'
import type Editor from 'wangeditor'

const props = withDefaults(
  defineProps<{
    value: string
    height?: number
    zIndex?: number
    focus?: boolean
  }>(),
  {
    height: 500,
    zIndex: 500,
    focus: true
  }
)
const emit = defineEmits(['update:value'])

const DivRef = ref<HTMLDivElement | null>(null)
const EInstance = ref<Editor | null>(null)
// 转换的reactive对象(html->text)
const shiftInfo = reactive<{ html: string; text: string }>({
  html: '',
  text: ''
})

onMounted(() => {
  EInstance.value = new E(DivRef.value)
  setEditorConfig()
  EInstance.value.create()
  // 默认设置值
  EInstance.value.txt.html(props.value)
  // 值变化时发射事件
  EInstance.value.config.onchange = function (newHtml: string) {
    shiftInfo.html = newHtml
    if (!EInstance.value) return
    // 拿到text传出去
    shiftInfo.text = EInstance.value.txt.text()
    emit('update:value', shiftInfo.text)
  }
})
// 将wangEditor进行销毁
onBeforeUnmount(() => {
  if (!EInstance.value) return
  EInstance.value.destroy()
  EInstance.value = null
})

const setEditorConfig = () => {
  if (!EInstance.value) return
  EInstance.value.config.height = props.height
  EInstance.value.config.placeholder = '请输入你的故事~'
  EInstance.value.config.zIndex = props.zIndex
  EInstance.value.config.focus = props.focus
  EInstance.value.config.onchangeTimeout = 500
  EInstance.value.config.menus = [
    'head',
    'bold',
    'fontSize',
    'fontName',
    'italic',
    'underline',
    'strikeThrough',
    'indent',
    'lineHeight',
    'foreColor',
    'backColor',
    'link',
    'list',
    // 'todo',
    'justify',
    'quote',
    // 'emoticon',
    // 'image',
    // 'video',
    // 'table',
    'code',
    'splitLine',
    'undo',
    'redo'
  ]
}
</script>

<style scoped lang="less">
.editor {
  text-align: left;
}
</style>
